#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <cctype>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

#include "Log.hpp"

using namespace std;

static void Usage(const string porc)
{
    cout << "Usage: " << porc << "port [ip]" << endl;
}

class UdpSever
{
public:
    UdpSever(int port,string ip = "")
        :_port(port), _ip(ip),_sockfd(-1)
    {}

    ~UdpSever()
    {}

    void inti()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM,0);
        if (_sockfd < 0)
        {
            logMessage(FATAL, "socket:%s:%d", strerror(errno), _sockfd);
            exit(1);
        }

        logMessage(DEBUG, "socket create success: %d", _sockfd);
        struct sockaddr_in local;
        bzero(&local, sizeof (local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty() ? htonl(INADDR_ANY) : inet_addr(_ip.c_str());

        if (bind(_sockfd, (const struct sockaddr*)&local, sizeof(local)) == -1)
        {
            logMessage(FATAL, "bind: %s:%d", strerror(errno), _sockfd);
            exit(2);
        }
        logMessage(DEBUG, "socket bind success: %d", _sockfd);
    }

    void start()
    {
        char inbuffer[1024];
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof (peer);
            ssize_t s = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0,
                        (struct sockaddr*)&peer, &len);
            if (s > 0)
            {
                inbuffer[s] = 0;       
            }
            else if (s == -1)
            {
                logMessage(WARINING, "recvfrom: %s:%d", strerror(errno), _sockfd);
                continue;
            }
            string peerIp = inet_ntoa(peer.sin_addr);
            uint16_t peerPort = ntohs(peer.sin_port);
            checkUser(peerIp, peerPort, peer);
            logMessage(NOTICE, "[%s:%d]# %s", peerIp.c_str(), peerPort, inbuffer);
            messageRoute(peerIp, peerPort, inbuffer);
        }
    }
   
    void checkUser(string ip, uint16_t port, struct sockaddr_in& peer)
    {
        string key = ip;
        key += ":";
        key += to_string(port);
        auto iter = _users.find(key);
        if (iter == _users.end())
        {
            _users.insert({key, peer});
        }
    }
    void messageRoute(string ip, uint16_t port, string buffer)
    {
        string message = "[";
        message += ip;
        message += ":";
        message += to_string(port);
        message += "]:";
        message += buffer;
        for (auto& user : _users)
        {
            sendto(_sockfd, message.c_str(), message.size(), 0,(struct sockaddr*)&user.second,sizeof(user.second));
        }
    }

private:
    uint16_t _port;
    string _ip;
    int _sockfd;
    unordered_map<string, struct sockaddr_in> _users;
};

int main(int argc, char* argv[])
{
    if (argc != 2 && argc != 3)
    {
        exit(3);
    }

    uint16_t port = atoi(argv[1]);
    string ip ;
    if (argc == 3)
    {
        ip = argv[2];
    }
    UdpSever svr(port, ip);
    svr.inti();
    svr.start();
    return 0;
}
